package cn.piesat.client.service.impl;

import cn.piesat.client.constant.consist.AppProperties;
import cn.piesat.client.model.dto.buiness.QsClientRunnerDto;
import cn.piesat.client.service.RedisSateService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Async("redisServiceThreePool")
@Service
public class RedisSateServiceImpl implements RedisSateService {

    @Autowired
    private AppProperties appProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 日志redis存储Key
     * AlgorithmLog:任务Id:算法Id:主文件名称
     */
    private static final String LOG_KEY_TEMPLATE = "AlgorithmLog:%s:%s:%s";

    /**
     * 流程redis存储Key
     * AlgorithmFlow:任务Id:算法Id:主文件名称
     */
//    private static final String FLOW_KEY_TEMPLATE = "AlgorithmFlow:%s:%s:%s";

    @Override
    public void healthInformation() {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String key = String.format("health:%s:%s", appProperties.getIp(),appProperties.getPort());
        valueOperations.set(key,"running",10, TimeUnit.MINUTES);
    }

    @Override
    public void recordStatus(QsClientRunnerDto runnerDto, boolean hasClean) {
        String logKey = String.format(LOG_KEY_TEMPLATE, runnerDto.getTaskId(), runnerDto.getAlgorithmId(),runnerDto.getFileName());
//        String flowKey = String.format(FLOW_KEY_TEMPLATE, runnerDto.getTaskId(), runnerDto.getAlgorithmId(),runnerDto.getFileName());

        File logFile = new File(runnerDto.getAlgorithmLogFile());
//        File flowFile = new File(runnerDto.getAlgorithmFlowFile());

        ValueOperations valueOperations = redisTemplate.opsForValue();
        if(logFile.exists()){
            try {
                String logStr = FileUtils.readFileToString(logFile, "UTF-8");
                valueOperations.set(logKey,logStr,10,TimeUnit.MINUTES);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(hasClean){
                logFile.deleteOnExit();
            }
        }
//        if(flowFile.exists()){
//            try {
//                String flowStr = FileUtils.readFileToString(flowFile, "UTF-8");
//                valueOperations.set(flowKey,flowStr,10,TimeUnit.MINUTES);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            if(hasClean){
//                flowFile.deleteOnExit();
//            }
//        }
    }
}
